/**
 * 精灵蔬菜构建工具
 */
import * as THREE from 'three'

export interface Position {
    x: number
    y: number
    z: number
}

export interface SpriteConfig {
    img: HTMLImageElement
    position: Position
}

export class Sprite {
    _canvas: any = null
    _ctx: any = null
    constructor() {
        this._canvas = document.createElement('canvas')
        this._ctx = this._canvas.getContext('2d')
        const devicePixelRatio = window.devicePixelRatio * 4
        const logicalWidth = 124
        const logicalHeight = 164
        this._canvas.width = logicalWidth * devicePixelRatio
        this._canvas.height = logicalHeight * devicePixelRatio
        this._canvas.style.width = `${logicalWidth}px`
        this._canvas.style.height = `${logicalHeight}px`
        this._ctx.scale(devicePixelRatio, devicePixelRatio)
    }

    _getCrop(config: SpriteConfig) {
        // 画图
        const imglong = 124
        const logicalWidth = 124
        const left = (logicalWidth - imglong) / 2;
        this._ctx.drawImage(config.img, left, 40, imglong, imglong); // 向下移动图片

        // 纹理图
        const texture = new THREE.CanvasTexture(this._canvas)
        texture.colorSpace = THREE.SRGBColorSpace
        texture.needsUpdate = true

        // 纹理生成材质
        const material = new THREE.SpriteMaterial({ map: texture })

        // 创建精灵几何体
        const sprite = new THREE.Sprite(material)
        sprite.center = new THREE.Vector2(0.5, 0)

        // 设置位置
        sprite.position.x = config.position.x
        sprite.position.y = config.position.y
        sprite.position.z = config.position.z

        return sprite
    }

}


